import React, { FC, useState , useEffect } from 'react'
import {Editor} from "react-draft-wysiwyg"   // Editor
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html"  // draft ===> html;
import htmlToDraft from "html-to-draftjs" //  html ===>  draft
import {EditorState,ContentState} from "draft-js"
import './index.scss'

const RichEditor:FC<any> = ({
    getContent,
    content
}) => {
    const [contentState,setContentState] = useState<any>()  // 富文本编辑的内容
    const [editorState,setEditorState] = useState<any>()    // 富文本编辑框的状态 
    const  onEditorStateChange = (state:any)=>{  // 修改编辑框的 state
        setEditorState(state)
    }
    const onContentStateChange = (content:any)=>{  // 修改编辑框的 内容   
        setContentState(content)
    }

    useEffect(()=>{
        if(!content){ // 父改子   默认的内容 
            return ;
        }
        
        // 修改  修改数据
        const html = content; 
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks); // 创建内容从 htmlToDraft
            const editorState = EditorState.createWithContent(contentState);// 创建编辑器状态 
            setEditorState(editorState)
        }
    },[])

    return (
        <Editor
            editorState={editorState}
            toolbarClassName="toolbarClassName" // DIY样式
            wrapperClassName="wrapperClassName" // DIY样式
            editorClassName="editorClassName" // DIY样式
            onEditorStateChange={onEditorStateChange}  
            onContentStateChange={onContentStateChange}
            onBlur={
                ()=>{
                    console.log(contentState)
                    if(contentState.blocks[0].text){
                        getContent(draftToHtml(contentState))  // 子改父 
                    }else{
                        getContent('')  // 子改父 
                    }
                }
            }
        />
    )
}

RichEditor.defaultProps = {
    getContent:()=>{}
}

export default RichEditor